package com.jic.product.controller.manage;


import com.jic.common.base.vo.RestResult;
import com.jic.product.entity.CategoryPropertyName;
import com.jic.product.entity.ProductPropertyName;
import com.jic.product.manage.request.ShopInfoRequest;
import com.jic.product.manage.request.UploadProductTemplateRequest;
import com.jic.product.manage.response.ProductPropertyNameResponse;
import com.jic.product.manage.response.ShopInfoResponse;
import com.jic.product.model.entity.MStoreOperateLog;
import com.jic.product.model.vo.request.MStoreOperateRequest;
import com.jic.product.service.*;
import com.jic.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by zxk on 2020/1/9 11:04
 * 商品导出
 */
@RestController
@RequestMapping("/productExcel")
@Api(value = "商品列表导出/导入", description = "商品列表导出/导入", tags = "商品列表导出/导入")
@Slf4j
public class ProductExcelController {

    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryPropertyNameService categoryPropertyNameService;
    @Autowired
    private ProductPropertyNameService productPropertyNameService;
    @Autowired
    private StoreInventoryService storeInventoryService;
    @Autowired
    private ProductUploadExceptionService productUploadExceptionService;

    @Autowired
    private MStoreOperateService mStoreOperateService;

    @ApiOperation(value = "店铺商品价格列表导出")
    @PostMapping("/shopProductPriceExcel")
    @ResponseBody
    public void shopProductPriceExcel(@RequestBody ShopInfoRequest shopInfoRequest, HttpServletResponse response) {
        log.info("开始进入商品店铺列表导出===============》" + shopInfoRequest.toString());
        response.setCharacterEncoding("UTF-8");
        String stringFromDate = DateUtil.getStringFromDate(new Date(), "yyyy-MM-dd");
        String fileName = "店铺商品列表" + stringFromDate + ".xls";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            HSSFWorkbook wb = new HSSFWorkbook();
            List<String> headers = new ArrayList<>();
            headers.add("商品id");
            headers.add("商品编码");
            headers.add("商品名称");
            headers.add("商品价格");
            HSSFSheet sheetSolution = wb.createSheet("店铺商品价格导出报表");
            HSSFRow rows = null;
            HSSFCell cells = null;
            rows = sheetSolution.createRow(0);
            HSSFCellStyle headStyle = wb.createCellStyle(); //表头
            headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
            headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
            DataFormat format = wb.createDataFormat();
            HSSFCellStyle numStyle = wb.createCellStyle(); //表头字体
            numStyle.setDataFormat(format.getFormat("#,##0.00")); //设置数据格式
            //列头创建
            for (int i = 0; i < headers.size(); i++) {
                cells = rows.createCell(i);
                cells.setCellValue(headers.get(i));
                cells.setCellStyle(headStyle);
                if (i == 0) {
                    sheetSolution.setColumnWidth(0, 2000);
                } else {
                    sheetSolution.setColumnWidth(i, 8000);
                }
            }

            List<ShopInfoResponse> shopInfoResponseList = productService.queryShopProductList(shopInfoRequest);
            if (CollectionUtils.isNotEmpty(shopInfoResponseList)) {
                //内容创建
                HSSFRow rowsContent = null;
                HSSFCell cellsContent = null;
                int index = 1;
                for (ShopInfoResponse shopInfoResponse : shopInfoResponseList) {
                    rowsContent = sheetSolution.createRow(index);
                    cellsContent = rowsContent.createCell(0);
                    cellsContent.setCellValue(shopInfoResponse.getId());
                    cellsContent = rowsContent.createCell(1);
                    cellsContent.setCellValue(shopInfoResponse.getCode());
                    cellsContent = rowsContent.createCell(2);
                    cellsContent.setCellValue(shopInfoResponse.getChineseName());
                    cellsContent = rowsContent.createCell(3);
                    cellsContent.setCellValue(String.valueOf(shopInfoResponse.getSalePriceWithTax()));
                    index++;
                }
                OutputStream out = null;
                out = response.getOutputStream();
                response.setContentType("application/msexcel;charset=GBK");
                wb.write(out);
                out.close();
            }
        } catch (Exception e) {
            log.error("shopProductPriceExcel==========>" + e);
        }
    }


    @ApiOperation(value = "店铺商品列表导入并修改价格")
    @PostMapping("/byExcelUpdateProductPrice")
    @ResponseBody
    public RestResult byExcelUpdateProductPrice(@RequestParam("file") MultipartFile file) throws Exception {
        return productPriceService.byExcelUpdateProductPrice(file.getOriginalFilename(), file);
    }

    @ApiOperation(value = "店铺商品库存列表导出")
    @PostMapping("/shopProductStockExcel")
    @ResponseBody
    public void shopProductStockExcel(@RequestBody ShopInfoRequest shopInfoRequest, HttpServletResponse response) {
        log.info("开始店铺商品库存列表导出===============》" + shopInfoRequest.toString());
        response.setCharacterEncoding("UTF-8");
        String stringFromDate = DateUtil.getStringFromDate(new Date(), "yyyy-MM-dd");
        String fileName = "店铺商品库存" + stringFromDate + ".xls";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            HSSFWorkbook wb = new HSSFWorkbook();
            List<String> headers = new ArrayList<>();
            headers.add("商品id");
            headers.add("商品编码");
            headers.add("商品名称");
            headers.add("商品库存");
            HSSFSheet sheetSolution = wb.createSheet("店铺商品库存列表");
            HSSFRow rows = null;
            HSSFCell cells = null;
            rows = sheetSolution.createRow(0);
            HSSFCellStyle headStyle = wb.createCellStyle(); //表头
            headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
            headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
            //列头创建
            for (int i = 0; i < headers.size(); i++) {
                cells = rows.createCell(i);
                cells.setCellValue(headers.get(i));
                cells.setCellStyle(headStyle);
                if (i == 0) {
                    sheetSolution.setColumnWidth(0, 2000);
                } else {
                    sheetSolution.setColumnWidth(i, 8000);
                }
            }

            List<ShopInfoResponse> shopInfoResponseList = productService.queryShopProductList(shopInfoRequest);
            if (CollectionUtils.isNotEmpty(shopInfoResponseList)) {
                //内容创建
                HSSFRow rowsContent = null;
                HSSFCell cellsContent = null;
                int index = 1;
                for (ShopInfoResponse shopInfoResponse : shopInfoResponseList) {
                    rowsContent = sheetSolution.createRow(index);
                    cellsContent = rowsContent.createCell(0);
                    cellsContent.setCellValue(shopInfoResponse.getId());
                    cellsContent = rowsContent.createCell(1);
                    cellsContent.setCellValue(shopInfoResponse.getCode());
                    cellsContent = rowsContent.createCell(2);
                    cellsContent.setCellValue(shopInfoResponse.getChineseName());
                    cellsContent = rowsContent.createCell(3);
                    cellsContent.setCellValue(String.valueOf(shopInfoResponse.getTotalStock()));
                    index++;
                }
                OutputStream out = null;
                out = response.getOutputStream();
                response.setContentType("application/msexcel;charset=GBK");
                wb.write(out);
                out.close();
            }
        } catch (Exception e) {
            log.error("shopProductStockExcel==========>" + e);
        }

    }


    @ApiOperation(value = "店铺商品列表导入并修改库存")
    @PostMapping("/byExcelUpdateProductStock")
    @ResponseBody
    public RestResult byExcelUpdateProductStock(@RequestParam("file") MultipartFile file) throws Exception {
        return storeInventoryService.byExcelUpdateProductStock(file.getOriginalFilename(), file);
    }


    @ApiOperation(value = "生成批量导入商品模板")
    @PostMapping("/batchUploadProductTemplate")
    @ResponseBody
    public void batchUploadProductTemplate(@RequestBody UploadProductTemplateRequest uploadProductTemplateRequest, HttpServletResponse response) throws Exception {
        log.info("开始进入生成批量导入商品模板===============》" + uploadProductTemplateRequest.toString());
        response.setCharacterEncoding("UTF-8");
        String stringFromDate = DateUtil.getStringFromDate(new Date(), "yyyy-MM-dd");
        String fileName = "店铺商品库存" + stringFromDate + ".xls";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            HSSFWorkbook wb = new HSSFWorkbook();
            List<String> headers = new ArrayList<>();
            List<String> headersCategory = new ArrayList<>();
            headers.add("*商品名称");
            headers.add("*商品编码");
            headers.add("第三方编码");
            headers.add("副标题");
            headers.add("*商品品牌");
            headers.add("*主计量单位");
            headers.add("商品条码");
            headers.add("货号");
            headers.add("产地");
            headers.add("净重g（起）");
            headers.add("净重g（止）");
            headers.add("是否支持发票（不填写则不支持）");
            headers.add("是否支持增票（不填写则不支持）");
            headers.add("是否强制发票（不填写则不强制）");
            headers.add("商品保障");
            headers.add("销售区域编码");
            headers.add("*零售价");
            headers.add("采购价");
            headers.add("团购价");
            //根据商品类目查询类目属性
            CategoryPropertyName categoryPropertyName = new CategoryPropertyName();
            categoryPropertyName.setCategoryId(uploadProductTemplateRequest.getCategoryId());
            List<CategoryPropertyName> list = categoryPropertyNameService.query(categoryPropertyName);
            List<ProductPropertyNameResponse> productPropertyNameResponseList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(item -> {
                    if (Long.valueOf(item.getAttNameId()) != null) {
                        ProductPropertyName productPropertyName = productPropertyNameService.queryByPrimaryKey(item.getAttNameId());
                        if (productPropertyName != null) {
                            headers.add(productPropertyName.getName());
                            //查询属性值
                            ProductPropertyNameResponse productPropertyNameResponse = productPropertyNameService.queryPropertyValueById(productPropertyName);
                            productPropertyNameResponseList.add(productPropertyNameResponse);
                        }
                    }
                });
            }
            HSSFSheet sheetSolution = wb.createSheet("商品模板");
            Font font = wb.createFont();
            font.setColor(Font.COLOR_RED);
            HSSFRow rows = null;
            HSSFCell cells = null;
            rows = sheetSolution.createRow(0);
            HSSFCellStyle headStyle = wb.createCellStyle(); //表头
            HSSFCellStyle headStyle1 = wb.createCellStyle(); //表头
            headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
            headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
            headStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
            headStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
            headStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            headStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER); //水平居中
            headStyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
            headStyle1.setFont(font);
            //商品模板列头创建
            for (int i = 0; i < headers.size(); i++) {
                cells = rows.createCell(i);
                cells.setCellValue(headers.get(i));
                sheetSolution.setColumnWidth(i, 5000);
                if (i == 0) {
                    cells.setCellStyle(headStyle1);
                } else if (i == 1) {
                    cells.setCellStyle(headStyle1);
                } else if (i == 1) {
                    cells.setCellStyle(headStyle1);
                } else if (i == 4) {
                    cells.setCellStyle(headStyle1);
                } else if (i == 5) {
                    cells.setCellStyle(headStyle1);
                } else if (i == 16) {
                    cells.setCellStyle(headStyle1);
                }
            }
            HSSFSheet sheetCategorySolution = wb.createSheet("类目模板");
            HSSFRow rowsCategory = null;
            HSSFCell cellsCategory = null;
            rowsCategory = sheetCategorySolution.createRow(0);
            //属性sheet表头
            headersCategory.add("属性名");
            headersCategory.add("属性值");
            //属性列头创建
            for (int i = 0; i < headersCategory.size(); i++) {
                cells = rowsCategory.createCell(i);
                cells.setCellValue(headersCategory.get(i));
                cells.setCellStyle(headStyle);
                sheetSolution.setColumnWidth(i, 8000);
            }
            //属性sheet数据
            if (CollectionUtils.isNotEmpty(productPropertyNameResponseList)) {
                int index = 1;
                for (ProductPropertyNameResponse productPropertyNameResponse : productPropertyNameResponseList) {
                    rowsCategory = sheetCategorySolution.createRow(index);
                    cellsCategory = rowsCategory.createCell(0);
                    cellsCategory.setCellValue(productPropertyNameResponse.getName());
                    cellsCategory = rowsCategory.createCell(1);
                    cellsCategory.setCellValue(productPropertyNameResponse.getProductPropertyValue());
                    index++;
                }
            }
            OutputStream out = null;
            out = response.getOutputStream();
            response.setContentType("application/msexcel;charset=GBK");
            wb.write(out);
            out.close();
        } catch (Exception e) {
            log.error("batchUploadProductTemplate==========>" + e);
        }
    }


    @ApiOperation(value = "批量新增商品")
    @PostMapping("/batchUploadProduct")
    @ResponseBody
    public RestResult batchUploadProduct(@RequestParam("file") MultipartFile file, @RequestParam Long categoryId, @RequestParam Integer typeOfProduct, @RequestParam Integer type, @RequestParam Long deptId) throws Exception {
        return productUploadExceptionService.batchUploadProduct(file.getOriginalFilename(), file, categoryId, typeOfProduct, type, deptId);
    }

    @ApiOperation(value = "库内事务数据导出")
    @PostMapping("/uploadStoreOperate")
    @ResponseBody
    public void uploadStoreOperate(@RequestBody MStoreOperateRequest mStoreOperateRequest, HttpServletResponse response) throws Exception {
        log.info("开始进入生库内事务数据导出===============》" + mStoreOperateRequest.toString());
        response.setCharacterEncoding("UTF-8");
        String fileName = "库内实物单据导出" + ".xls";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            HSSFWorkbook wb = new HSSFWorkbook();
            List<String> headers = new ArrayList<>();
            headers.add("商家");
            headers.add("单据类型");
            headers.add("单据编号");
            headers.add("单据状态");
            headers.add("申请数量");
            headers.add("实际处理数量");
            headers.add("创建日期");
            headers.add("创建人");
            headers.add("最后更新日期");
            headers.add("最后更新人");
            HSSFSheet sheetSolution = wb.createSheet("库内实物单据");
            HSSFRow rows = null;
            HSSFCell cells = null;
            rows = sheetSolution.createRow(0);
            CellStyle cellStyle = wb.createCellStyle();
            CreationHelper createHelper = wb.getCreationHelper();
            short dateFormat = createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss");
            cellStyle.setDataFormat(dateFormat);
            //列头创建
            for (int i = 0; i < headers.size(); i++) {
                cells = rows.createCell(i);
                cells.setCellValue(headers.get(i));
                sheetSolution.setColumnWidth(i, 5000);
            }
            //获取数据清单
            List<MStoreOperateLog> operateList = mStoreOperateService.listExcel(mStoreOperateRequest);
            if (CollectionUtils.isNotEmpty(operateList)) {
                for (int j = 0; j < operateList.size(); j++) {
                    rows = sheetSolution.createRow(j+1);
                    for (int i = 0; i < headers.size(); i++) {
                        cells = rows.createCell(i);
                        if (i == 0) {
                            if (null != operateList.get(j).getDeptId()) {
                                cells.setCellValue(operateList.get(j).getDeptId());
                            }
                        } else if (i == 1) {
                            if (null != operateList.get(j).getOperateDesc()) {
                                cells.setCellValue(operateList.get(j).getOperateDesc());
                            }
                        } else if (i == 2) {
                            if (null != operateList.get(j).getCode()) {
                                cells.setCellValue(operateList.get(j).getCode());
                            }
                        } else if (i == 3) {
                            cells.setCellValue(operateList.get(j).getStatus() == 0 ? "待处理" : "已完成");
                        } else if (i == 4) {
                            if (null != operateList.get(j).getApplyNum()) {
                                cells.setCellValue(operateList.get(j).getApplyNum());
                            }
                        } else if (i == 5) {
                            if (null != operateList.get(j).getActualNum()) {
                                cells.setCellValue(operateList.get(j).getActualNum());

                            }
                        } else if (i == 6) {
                            if (null != operateList.get(j).getCreateTime()) {
                                cells.setCellValue(operateList.get(j).getCreateTime());
                                cells.setCellStyle(cellStyle);
                            }
                        } else if (i == 7) {
                            if (null != operateList.get(j).getCreator()) {
                                cells.setCellValue(operateList.get(j).getCreator());
                            }
                        } else if (i == 8) {
                            if (null != operateList.get(j).getUpdateTime()) {
                                cells.setCellValue(operateList.get(j).getUpdateTime());
                                cells.setCellStyle(cellStyle);
                            }
                        } else {
                            if (null != operateList.get(j).getUpdater()) {
                                cells.setCellValue(operateList.get(j).getUpdater());
                            }
                        }
                    }
                }
            }

            OutputStream out = null;
            out = response.getOutputStream();
            response.setContentType("application/msexcel;charset=GBK");
            wb.write(out);
            out.close();
        } catch (Exception e) {
            log.error("uploadStoreOperate==========>" + e);
        }
    }

    @ApiOperation(value = "库内事物单详情导入")
    @PostMapping("/mStoreOperateDetailExcel")
    @ResponseBody
    public RestResult mStoreOperateDetailExcel(@RequestParam("file") MultipartFile file, @RequestParam("deptId") Long deptId) throws Exception {
        return mStoreOperateService.mStoreOperateDetailExcel(file.getOriginalFilename(), file, deptId);
    }
}
